<template>
  <div class="dashboard-container">
    <!-- 成本看板整体卡片 -->
    <div class="cost-overview-container">
      <!-- 标题区域 -->
      <div class="overview-header">
        <h1 class="page-title">成本看板</h1>
        <div class="header-controls">
          <!-- 日月年选择器 -->
          <div class="date-type-selector">
            <span
              v-for="type in dateTypes"
              :key="type.value"
              :class="{ active: activeDateType === type.value }"
              @click="handleDateTypeChange(type.value)"
            >
              {{ type.label }}
            </span>
          </div>
          
          <!-- 日期选择器 -->
          <el-date-picker
            v-model="selectedDate"
            :type="datePickerType"
            :format="dateFormat"
            :value-format="dateFormat"
            placeholder="选择日期"
            class="date-picker"
            @change="handleDateChange"
          />
          
          <!-- 搜索按钮 -->
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>

      <!-- 成本概览卡片 -->
      <div class="cost-overview">
        <div class="cost-card" v-for="cost in costData" :key="cost.type">
          <div class="card-icon" :style="{ backgroundColor: cost.color }">
            <svg-icon :icon-class="cost.icon" />
          </div>
          <div class="card-content">
            <div class="card-title">{{ cost.name }}</div>
            <div class="card-value">
              <count-to
                :end-val="parseFloat(cost.value)"
                :decimals="2"
                :duration="2000"
                :font-size="'20px'"
                :font-weight="'600'"
                :color="'#303133'"
              />
              <span class="unit">{{ cost.unit }}</span>
            </div>
            <div class="card-trend" v-if="cost.trend">
              <span class="trend-label">{{ cost.trend.label }}:</span>
              <span
                class="trend-value"
                :class="{
                  positive: cost.type === 'comparison' ? cost.trend.value < 0 : cost.trend.value > 0,
                  negative: cost.type === 'comparison' ? cost.trend.value > 0 : cost.trend.value < 0,
                }"
              >
                {{ cost.trend.value > 0 ? "+" : "" }}{{ cost.trend.value }}%
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 左侧：电力峰谷时段成本分析 -->
      <div class="chart-container peak-valley-chart">
        <div class="chart-header">
          <h3>电力峰谷时段成本分析</h3>
          <p>各时段成本统计(单位 元)</p>
        </div>
        <div class="chart-content">
          <v-chart class="chart" :option="peakValleyChartOption" />
        </div>
      </div>

      <!-- 右侧：电力峰谷时段成本分布 -->
      <div class="chart-container cost-distribution-chart">
        <div class="chart-header">
          <h3>电力峰谷时段成本分布</h3>
          <p>各时段成本占比(单位 元)</p>
        </div>
        <div class="chart-content">
          <v-chart class="chart" :option="costDistributionChartOption" />
        </div>
      </div>
    </div>

    <!-- 底部图表区域 -->
    <div class="bottom-charts">
      <!-- 左侧：能源成本堆叠趋势分析 -->
      <div class="chart-container energy-cost-trend-chart">
        <div class="chart-header">
          <h3>能源成本堆叠趋势分析</h3>
          <p>各能源类型成本趋势(单位 元)</p>
        </div>
        <div class="chart-content">
          <v-chart class="chart" :option="energyCostTrendChartOption" />
        </div>
      </div>

      <!-- 右侧：能源成本明细 -->
      <div class="chart-container energy-cost-details">
        <div class="chart-header">
          <h3>能源成本明细</h3>
          <p>各能源类型成本统计(单位 元)</p>
        </div>
        <div class="chart-content">
          <div class="cost-details-list">
            <div
              class="cost-detail-item"
              v-for="(item, index) in energyCostDetails"
              :key="index"
            >
              <div class="detail-info">
                <div class="detail-name">{{ item.name }}</div>
                <div class="detail-consumption">{{ item.consumption }}</div>
                <div class="detail-cost">¥{{ item.cost }}</div>
                <div class="detail-proportion">{{ item.proportion }}% 占比</div>
              </div>
              <div class="detail-bar">
                <div
                  class="bar-fill"
                  :style="{
                    width: item.proportion + '%',
                    backgroundColor: item.color,
                  }"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { BarChart, PieChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import VChart from "vue-echarts";
import { ElDatePicker } from 'element-plus';
import CountTo from "@/components/CountTo/index.vue";
import { getStatisticsCost,getHourElectricityCostTypePieStatistics,getHourElectricityCostTypeListStatistics,getHourStatisticsTypeGroupListStatistics,getHourStatisticsTypePieStatistics } from "@/api/stat/cost";

// Register ECharts components
use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
]);

// 日期类型选择
const activeDateType = ref('day');
const selectedDate = ref('');

// 日期类型选项
const dateTypes = [
  { label: '日', value: 'day' },
  { label: '月', value: 'month' },
  { label: '年', value: 'year' }
];

// 计算属性：日期选择器类型
const datePickerType = computed(() => {
  switch (activeDateType.value) {
    case 'day':
      return 'date';
    case 'month':
      return 'month';
    case 'year':
      return 'year';
    default:
      return 'date';
  }
});

// 计算属性：日期格式
const dateFormat = computed(() => {
  switch (activeDateType.value) {
    case 'day':
      return 'YYYY-MM-DD';
    case 'month':
      return 'YYYY-MM';
    case 'year':
      return 'YYYY';
    default:
      return 'YYYY-MM-DD';
  }
});

// 成本数据
const costData = reactive([
  {
    type: "current_cost",
    name: "当期综合能耗",
    value: "1237.3",
    unit: "tce",
    icon: "chart",
    color: "#16A5B7",
  },
  {
    type: "current_total_cost",
    name: "当期总成本",
    value: "997.91",
    unit: "元",
    icon: "money",
    color: "#409EFF",
  },
  {
    type: "previous_total_cost",
    name: "上期总成本",
    value: "1796.27",
    unit: "元",
    icon: "money",
    color: "#67C23A",
  },
  {
    type: "comparison",
    name: "成本对比",
    value: "44.45",
    unit: "%",
    icon: "money",
    color: "#4fdaca",
    trend: {
      label: "环比",
      value: -44.45,
    },
  },
]);

// 峰谷时段数据
const peakValleyData = reactive([
  { time: "00时", cost: 23.5, type: "深谷" },
  { time: "02时", cost: 24.2, type: "深谷" },
  { time: "04时", cost: 23.8, type: "深谷" },
  { time: "06时", cost: 24.1, type: "谷" },
  { time: "08时", cost: 49.8, type: "平" },
  { time: "10时", cost: 50.2, type: "平" },
  { time: "12时", cost: 70.5, type: "峰" },
  { time: "14时", cost: 30.8, type: "谷" },
  { time: "16时", cost: 15.6, type: "谷" },
  { time: "18时", cost: 0, type: "谷" },
  { time: "20时", cost: 0, type: "谷" },
  { time: "22时", cost: 0, type: "谷" },
]);

// 峰谷时段成本分布数据
const costDistributionData = reactive([
  { name: "尖", value: 0.0, color: "#16A5B7" },
  { name: "峰", value: 147.28, color: "#7bfbc8" },
  { name: "平", value: 147.26, color: "#409EFF" },
  { name: "深谷", value: 171.92, color: "#4fdaca" },
  { name: "谷", value: 144.02, color: "#32b7cb" },
]);

// 能源成本明细数据
const energyCostDetails = reactive([
  {
    name: "电",
    consumption: "769.05千瓦时",
    cost: "610.48",
    proportion: 61.18,
    color: "#FFD700",  // 黄色
  },
  {
    name: "蒸汽",
    consumption: "18.55立方米",
    cost: "153.05",
    proportion: 15.34,
    color: "#F56C6C",  // 红色（热）
  },
  {
    name: "压缩空气",
    consumption: "30.89立方米",
    cost: "131.29",
    proportion: 13.16,
    color: "#F56C6C",  // 红色（热）
  },
  {
    name: "气",
    consumption: "20.11立方米",
    cost: "62.55",
    proportion: 6.27,
    color: "#909399",  // 灰色
  },
  {
    name: "水",
    consumption: "7.93吨",
    cost: "40.52",
    proportion: 4.06,
    color: "#409EFF",  // 蓝色
  },
]);

// 能源成本堆叠趋势数据
const energyCostTrendData = reactive([
  { time: "00时", 电: 20, 水: 5, 气: 8, 蒸汽: 15, 压缩空气: 12 },
  { time: "02时", 电: 18, 水: 4, 气: 7, 蒸汽: 14, 压缩空气: 11 },
  { time: "04时", 电: 22, 水: 6, 气: 9, 蒸汽: 16, 压缩空气: 13 },
  { time: "06时", 电: 25, 水: 7, 气: 10, 蒸汽: 18, 压缩空气: 15 },
  { time: "08时", 电: 45, 水: 12, 气: 18, 蒸汽: 25, 压缩空气: 22 },
  { time: "10时", 电: 55, 水: 15, 气: 22, 蒸汽: 30, 压缩空气: 28 },
  { time: "12时", 电: 65, 水: 18, 气: 25, 蒸汽: 35, 压缩空气: 32 },
  { time: "14时", 电: 70, 水: 20, 气: 28, 蒸汽: 38, 压缩空气: 35 },
  { time: "16时", 电: 40, 水: 10, 气: 15, 蒸汽: 20, 压缩空气: 18 },
  { time: "18时", 电: 30, 水: 8, 气: 12, 蒸汽: 15, 压缩空气: 14 },
  { time: "20时", 电: 25, 水: 6, 气: 10, 蒸汽: 12, 压缩空气: 11 },
  { time: "22时", 电: 20, 水: 5, 气: 8, 蒸汽: 10, 压缩空气: 9 },
]);

// 峰谷时段成本分析图表配置
const peakValleyChartOption = computed(() => ({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
    formatter: function (params) {
      const data = params[0];
      return `${data.name}<br/>成本: ${data.value}元<br/>时段: ${data.data.type}`;
    },
  },
  legend: {
    data: ["尖", "峰", "平", "深谷", "谷"],
    top: 10,
    textStyle: {
      color: "#606266",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: peakValleyData.map((item) => item.time),
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
  },
  yAxis: {
    type: "value",
    name: "单位(元)",
    nameTextStyle: {
      color: "#606266",
    },
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
    splitLine: {
      lineStyle: {
        color: "#E4E7ED",
        type: "dashed",
      },
    },
  },
  series: [
    {
      name: "成本",
      type: "bar",
      data: peakValleyData.map((item) => ({
        value: item.cost,
        type: item.type,
        itemStyle: {
          color: getTypeColor(item.type),
        },
      })),
      barWidth: "60%",
    },
  ],
}));

// 成本分布环形图配置
const costDistributionChartOption = computed(() => ({
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b}: {c}元 ({d}%)",
  },
  legend: {
    orient: "vertical",
    right: 10,
    top: "center",
    textStyle: {
      color: "#606266",
    },
    formatter: function (name) {
      const item = costDistributionData.find((d) => d.name === name);
      return `${name}: ${item.value}元`;
    },
  },
  series: [
    {
      name: "成本分布",
      type: "pie",
      radius: ["40%", "70%"],
      center: ["40%", "50%"],
      avoidLabelOverlap: false,
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: "14",
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: costDistributionData.map((item) => ({
        value: parseFloat(item.value),
        name: item.name,
        itemStyle: {
          color: item.color,
        },
      })),
    },
  ],
}));

// 能源成本堆叠趋势分析图表配置
const energyCostTrendChartOption = computed(() => {
  // 定义能源类型颜色映射
  const energyColorMap = {
    '电': '#FFD700',      // 黄色
    '水': '#409EFF',      // 蓝色
    '气': '#909399',      // 灰色
    '蒸汽': '#F56C6C',    // 红色（热）
    '压缩空气': '#F56C6C', // 红色（热）
    '光伏': '#67C23A'     // 绿色
  };
  
  // 从数据中提取所有能源类型
  const energyTypes = new Set();
  energyCostTrendData.forEach(item => {
    Object.keys(item).forEach(key => {
      if (key !== 'time') {
        energyTypes.add(key);
      }
    });
  });
  
  const types = Array.from(energyTypes);
  
  // 动态生成 series
  const series = types.map(typeName => ({
    name: typeName,
    type: "bar",
    stack: "total",
    data: energyCostTrendData.map((item) => item[typeName] || 0),
    itemStyle: {
      color: energyColorMap[typeName] || '#409EFF',
    },
  }));
  
  return {
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
    },
  },
  legend: {
      data: types,
    top: 10,
    textStyle: {
      color: "#606266",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    data: energyCostTrendData.map((item) => item.time),
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
  },
  yAxis: {
    type: "value",
    name: "单位(元)",
    nameTextStyle: {
      color: "#606266",
    },
    axisLabel: {
      color: "#606266",
    },
    axisLine: {
      lineStyle: {
        color: "#E4E7ED",
      },
    },
    splitLine: {
      lineStyle: {
        color: "#E4E7ED",
        type: "dashed",
      },
    },
  },
    series: series,
  };
});

// 获取时段类型对应的颜色
function getTypeColor(type) {
  const colorMap = {
    尖: "#16A5B7",
    峰: "#7bfbc8",
    平: "#409EFF",
    深谷: "#4fdaca",
    谷: "#32b7cb",
  };
  return colorMap[type] || "#16A5B7";
}

// 处理日期类型变化
const handleDateTypeChange = (type) => {
  activeDateType.value = type;
  
  const now = new Date();
  // 根据类型调整默认日期
  switch (type) {
    case "day":
      selectedDate.value = now.toISOString().split('T')[0];
      break;
    case "month":
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      selectedDate.value = `${year}-${month}`;
      break;
    case "year":
      selectedDate.value = String(now.getFullYear());
      break;
  }
};

// 处理日期变化
const handleDateChange = (date) => {
  selectedDate.value = date;
  console.log("日期变化:", date);
};

// 加载成本汇总数据
const loadCostSummary = async () => {
  try {
    const params = {
      statTime: selectedDate.value
    };
    
    console.log('调用成本统计接口，参数:', params);
    
    const response = await getStatisticsCost(params);
    
    console.log('成本统计接口返回数据:', response);
    
    if (response && response.code === 200 && response.data) {
      const { dayData, beforedayData } = response.data;
      
      if (dayData) {
        // 当期综合能耗（carbonEmissions）
        const currentEnergy = dayData.carbonEmissions || 0;
        // 当期总成本（cost_money）
        const currentCost = dayData.cost_money || 0;
        // 上期总成本
        const previousCost = beforedayData ? (beforedayData.cost_money || 0) : 0;
        
        // 计算环比
        let costComparison = 0;
        if (previousCost !== 0) {
          costComparison = ((currentCost - previousCost) / previousCost * 100).toFixed(2);
        } else if (currentCost !== 0) {
          costComparison = 100;
        }
        
        // 更新卡片数据
        costData[0].value = currentEnergy.toFixed(2);
        costData[1].value = currentCost.toFixed(2);
        costData[2].value = previousCost.toFixed(2);
        costData[3].value = Math.abs(parseFloat(costComparison)).toFixed(2);
        
        // 更新成本对比的趋势
        if (costData[3].trend) {
          costData[3].trend.value = parseFloat(costComparison);
        }
        
        console.log('成功更新成本卡片数据');
      }
    }
  } catch (error) {
    console.error('加载成本汇总数据失败:', error);
  }
};

// 加载电力峰谷时段成本分布数据（饼图）
const loadPeakValleyCostData = async () => {
  try {
    const params = {
      statTime: selectedDate.value
    };
    
    console.log('调用电力峰谷时段成本分布接口，参数:', params);
    
    const response = await getHourElectricityCostTypePieStatistics(params);
    
    console.log('电力峰谷时段成本分布接口返回数据:', response);
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.stats;
      if (stats && stats.length > 0) {
        // 清空原有数据
        costDistributionData.length = 0;
        
        // 定义类型名称和颜色映射
        const typeNameMap = {
          '尖峰': '尖',
          '高峰': '峰',
          '平段': '平',
          '深谷': '深谷',
          '谷段': '谷'
        };
        
        const colorMap = {
          '尖峰': '#16A5B7',
          '高峰': '#7bfbc8',
          '平段': '#409EFF',
          '深谷': '#4fdaca',
          '谷段': '#32b7cb'
        };
        
        stats.forEach(item => {
          const costType = item.costType;
          costDistributionData.push({
            name: typeNameMap[costType] || costType,
            value: parseFloat(item.cost_money || 0).toFixed(2),
            color: colorMap[costType] || '#16A5B7'
          });
        });
        
        console.log('成功更新电力峰谷时段成本分布数据');
      }
    }
  } catch (error) {
    console.error('加载电力峰谷时段成本分布数据失败:', error);
  }
};

// 加载电力峰谷时段成本分析数据（柱状图）
const loadPeakValleyChartData = async () => {
  try {
    const params = {
      statTime: selectedDate.value
    };
    
    console.log('调用电力峰谷时段成本分析接口，参数:', params);
    
    const response = await getHourElectricityCostTypeListStatistics(params);
    
    console.log('电力峰谷时段成本分析接口返回数据:', response);
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.stats;
      if (stats && stats.length > 0) {
        // 清空原有数据
        peakValleyData.length = 0;
        
        // 定义类型名称映射
        const typeNameMap = {
          '尖峰': '尖',
          '高峰': '峰',
          '平段': '平',
          '深谷': '深谷',
          '谷段': '谷'
        };
        
        stats.forEach(item => {
          // hourName 格式如 "2025-10-14 00:00" 或 "00:00"
          let timeLabel = '';
          if (item.hourName) {
            const parts = item.hourName.split(' ');
            if (parts.length > 1) {
              // 有日期部分，取时间部分
              const timePart = parts[1].split(':')[0];
              timeLabel = timePart.padStart(2, '0') + '时';
            } else {
              // 只有时间部分
              const timePart = parts[0].split(':')[0];
              timeLabel = timePart.padStart(2, '0') + '时';
            }
          }
          
          peakValleyData.push({
            time: timeLabel,
            cost: parseFloat((parseFloat(item.cost_money || 0)).toFixed(2)),
            type: typeNameMap[item.costType] || item.costType
          });
        });
        
        console.log('成功更新电力峰谷时段成本分析数据');
      }
    }
  } catch (error) {
    console.error('加载电力峰谷时段成本分析数据失败:', error);
  }
};

// 加载能源成本堆叠趋势分析数据
const loadEnergyCostTrendData = async () => {
  try {
    const params = {
      statTime: selectedDate.value
    };
    
    console.log('调用能源成本堆叠趋势分析接口，参数:', params);
    
    const response = await getHourStatisticsTypeGroupListStatistics(params);
    
    console.log('能源成本堆叠趋势分析接口返回数据:', response);
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.stats;
      if (stats && stats.length > 0) {
        // 清空原有数据
        energyCostTrendData.length = 0;
        
        // 按时间分组数据
        const groupedByTime = {};
        const energyTypes = new Set(); // 收集所有能源类型
        
        stats.forEach(item => {
          // hourName 格式如 "2025-10-07 00:00"
          let timeLabel = '';
          if (item.hourName) {
            const parts = item.hourName.split(' ');
            if (parts.length > 1) {
              const timePart = parts[1].split(':')[0];
              timeLabel = timePart.padStart(2, '0') + '时';
            } else {
              const timePart = parts[0].split(':')[0];
              timeLabel = timePart.padStart(2, '0') + '时';
            }
          }
          
          const typeName = item.statisticsTypeName;
          energyTypes.add(typeName); // 记录能源类型
          
          // 如果这个时间点还没有记录，创建一个
          if (!groupedByTime[timeLabel]) {
            groupedByTime[timeLabel] = {
              time: timeLabel
            };
          }
          
          // 根据能源类型分配成本
          const costMoney = parseFloat((parseFloat(item.cost_money || 0)).toFixed(2));
          
          // 直接使用 statisticsTypeName 作为键
          if (!groupedByTime[timeLabel][typeName]) {
            groupedByTime[timeLabel][typeName] = 0;
          }
          groupedByTime[timeLabel][typeName] += costMoney;
        });
        
        // 将分组后的数据转换为数组，并按时间排序
        const sortedData = Object.values(groupedByTime).sort((a, b) => {
          const timeA = parseInt(a.time.replace('时', ''));
          const timeB = parseInt(b.time.replace('时', ''));
          return timeA - timeB;
        });
        
        // 添加到 energyCostTrendData
        sortedData.forEach(item => {
          energyCostTrendData.push(item);
        });
        
        console.log('成功更新能源成本堆叠趋势分析数据');
      }
    }
  } catch (error) {
    console.error('加载能源成本堆叠趋势分析数据失败:', error);
  }
};

// 加载能源成本明细数据
const loadEnergyCostDetailsData = async () => {
  try {
    const params = {
      statTime: selectedDate.value
    };
    
    console.log('调用能源成本明细接口，参数:', params);
    
    const response = await getHourStatisticsTypePieStatistics(params);
    
    console.log('能源成本明细接口返回数据:', response);
    
    if (response && response.code === 200 && response.data) {
      const stats = response.data.stats;
      if (stats && stats.length > 0) {
        // 清空原有数据
        energyCostDetails.length = 0;
        
        // 按能源类型分组并汇总（因为可能有多个时间点的数据）
        const groupedByType = {};
        
        stats.forEach(item => {
          const typeName = item.statisticsTypeName;
          const cost = parseFloat(item.cost_money || 0);
          const consumption = parseFloat(item.sum_value || 0);
          
          if (!groupedByType[typeName]) {
            groupedByType[typeName] = {
              cost: 0,
              consumption: 0
            };
          }
          
          groupedByType[typeName].cost += cost;
          groupedByType[typeName].consumption += consumption;
        });
        
        // 计算总成本（用于占比）
        let totalCost = 0;
        Object.values(groupedByType).forEach(data => {
          totalCost += data.cost;
        });
        
        // 定义能源类型单位和颜色映射
        const energyUnitMap = {
          '电': '千瓦时',
          '水': '吨',
          '气': '立方米',
          '蒸汽': '立方米',
          '压缩空气': '立方米',
          '光伏': '千瓦时'
        };
        
        const energyColorMap = {
          '电': '#FFD700',      // 黄色
          '水': '#409EFF',      // 蓝色
          '气': '#909399',      // 灰色
          '蒸汽': '#F56C6C',    // 红色（热）
          '压缩空气': '#F56C6C', // 红色（热）
          '光伏': '#67C23A'     // 绿色
        };
        
        // 转换为显示格式
        Object.keys(groupedByType).forEach(typeName => {
          const data = groupedByType[typeName];
          const cost = data.cost;
          const consumption = data.consumption;
          const proportion = totalCost > 0 ? ((cost / totalCost) * 100).toFixed(2) : 0;
          
          const unit = energyUnitMap[typeName] || '';
          const color = energyColorMap[typeName] || '#409EFF';
          
          energyCostDetails.push({
            name: typeName,  // 直接使用 statisticsTypeName
            consumption: `${consumption.toFixed(2)}${unit}`,
            cost: cost.toFixed(2),
            proportion: parseFloat(proportion),
            color: color
          });
        });
        
        console.log('成功更新能源成本明细数据');
      }
    }
  } catch (error) {
    console.error('加载能源成本明细数据失败:', error);
  }
};

// 处理搜索
const handleSearch = async () => {
  if (!selectedDate.value) {
    console.warn('请选择日期');
    return;
  }
  
  console.log("搜索参数:", {
    dateType: activeDateType.value,
    selectedDate: selectedDate.value,
  });
  
  // 加载所有数据
  await Promise.all([
    loadCostSummary(),
    loadPeakValleyCostData(),
    loadPeakValleyChartData(),
    loadEnergyCostTrendData(),
    loadEnergyCostDetailsData()
  ]);
};

// 页面初始化
onMounted(() => {
  // 初始化为当天日期
  const now = new Date();
  selectedDate.value = now.toISOString().split('T')[0];
  
  // 加载初始数据
  loadCostSummary();
  loadPeakValleyCostData();
  loadPeakValleyChartData();
  loadEnergyCostTrendData();
  loadEnergyCostDetailsData();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background: #f1f2f5;
  height: 100%;
  overflow-y: auto;
}

.cost-overview-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;

  .overview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 20px 0 20px;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f0f0;

    .page-title {
      font-size: 20px;
      font-weight: 600;
      color: #1a1a1a;
      margin: 0;
      position: relative;

      &::before {
        content: "";
        position: absolute;
        left: -12px;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: linear-gradient(135deg, #16a5b7, #4fdaca);
        border-radius: 2px;
      }
    }
    
    .header-controls {
      display: flex;
      align-items: center;
      gap: 16px;

      .date-type-selector {
        display: flex;
        gap: 4px;
        background: #f8f9fa;
        padding: 4px;
        border-radius: 12px;
        border: 1px solid #e9ecef;

        span {
          padding: 8px 16px;
          border-radius: 8px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          color: #6c757d;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

          &.active {
            background: linear-gradient(135deg, #16a5b7, #4fdaca);
            color: white;
            box-shadow: 0 4px 12px rgba(22, 165, 183, 0.3);
          }

          &:hover:not(.active) {
            background: white;
            color: #16a5b7;
          }
        }
      }

      .date-picker {
        :deep(.el-input__wrapper) {
          border-radius: 6px;
          border: 1px solid #dcdfe6;

          &:hover {
            border-color: #16a5b7;
          }

          &.is-focus {
            border-color: #16a5b7;
            box-shadow: 0 0 0 2px rgba(22, 165, 183, 0.2);
          }
        }

        :deep(.el-input__inner) {
          font-size: 14px;
          color: #606266;
        }
      }

      .search-btn {
        padding: 10px 20px;
        background: #16a5b7;
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background: #4fdaca;
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(22, 165, 183, 0.3);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  .cost-overview {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    padding: 0 20px 20px 20px;

    .cost-card {
      background: #fafbfc;
      border-radius: 8px;
      padding: 16px;
      border: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      gap: 12px;
      transition: all 0.3s ease;

      &:hover {
        background: #f8f9fa;
        border-color: #16a5b7;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .card-icon {
        width: 44px;
        height: 44px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #16a5b7 !important;

        .svg-icon {
          font-size: 20px;
          color: #fff !important;
        }
      }

      .card-content {
        flex: 1;

        .card-title {
          font-size: 13px;
          color: #606266;
          margin-bottom: 6px;
          font-weight: 500;
          line-height: 1.2;
        }

        .card-value {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
          display: flex;
          align-items: baseline;
          gap: 3px;

          .unit {
            font-size: 12px;
            color: #909399;
            font-weight: normal;
          }
        }

        .card-trend {
          font-size: 11px;
          margin-bottom: 2px;

          .trend-label {
            color: #909399;
          }

          .trend-value {
            margin-left: 3px;

            &.positive {
              color: #67c23a;
            }

            &.negative {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.bottom-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .chart-header {
    padding: 20px 20px 0 20px;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f0f0;

    .header-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 16px;
    }

    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #1a1a1a;
      margin: 0;
      position: relative;
      line-height: 1.2;

      &::before {
        content: "";
        position: absolute;
        left: -12px;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: linear-gradient(135deg, #16a5b7, #4fdaca);
        border-radius: 2px;
      }
    }

    p {
      font-size: 14px;
      color: #666;
      margin: 0;
      font-weight: 500;
    }
  }

  .chart-content {
    padding: 20px;
    height: 400px;

    .chart {
      width: 100%;
      height: 100%;
    }
  }
}

.energy-cost-details {
  .cost-details-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .cost-detail-item {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .detail-info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .detail-name {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        flex: 1;
      }

      .detail-consumption {
        font-size: 12px;
        color: #909399;
        margin-right: 12px;
      }

      .detail-cost {
        font-size: 14px;
        font-weight: 600;
        color: #16a5b7;
        margin-right: 8px;
      }

      .detail-proportion {
        font-size: 12px;
        color: #606266;
        font-weight: 500;
      }
    }

    .detail-bar {
      height: 8px;
      background-color: #f0f0f0;
      border-radius: 4px;
      overflow: hidden;

      .bar-fill {
        height: 100%;
        border-radius: 4px;
        transition: width 0.3s ease;
      }
    }
  }
}
</style>
